<style lang="less">
    @import '../../styles/common.less';
</style>

<template>
  <div>
      <Row>
        <Col span="24">
            <Card>
                <p slot="title">
                    新闻列表
                </p>
                <Row>
                    <Col span="16">
                        <Input style="width:150px" @on-keyup.enter="getData" v-model="searchData.title" placeholder="输入名称搜索"></Input>
                        <Button type="primary" shape="circle" icon="ios-search" @click="getData"></Button>
                    </Col>
                    <Col span="3" offset="5" v-if="$hasPerms('news:save')">
                        <span style="margin: 0 10px;">      
                            <router-link :to="{name:'news_add'}">
                                <Button type="primary" icon="plus">新增新闻</Button>
                            </router-link>                    
                        </span>
                    </Col>
                </Row>
                <br>
                <Row>
                    <div class="edittable-table-height-con">
                        <Table stripe :loading="isLoading"
                            :columns="columns" :data="matchs" border disabled-hover></Table>
                            <div style="margin: 10px;overflow: hidden">
                                <div style="float: right;">
                                    <Page :total="total" :current="currentPage" :page-size="20" @on-change="changePage" show-elevator></Page>
                                </div>
                            </div>
                    </div>
                </Row>
            </Card>
        </Col>
      </Row>
  </div>

</template>

<script>
export default {
    name: 'news-index',
    data () {
        return {
            isLoading: true,
            saveLoading: false,
            searchData: {
                companyId: JSON.parse(localStorage.admin).companyId
            },
            // 表头
            columns: [
                {
                    title: '标题',
                    align: 'center',
                    key: 'title'
                },
                {
                    title: '封面',
                    align: 'center',
                    render: (h, params) => {
                        const val = params.row;
                        return h('a',
                            {
                                attrs: {
                                    href: val.cover,
                                    target: '_black'
                                }
                            },
                            [
                                h('img', {
                                    attrs: {
                                        src: val.cover,
                                        width: '100px',
                                        height: '50px'
                                    }
                                })
                            ]
                        );
                    }
                },
                {
                    title: '城市',
                    align: 'center',
                    key: 'matchCity'
                },
                {
                    title: '是否热门',
                    align: 'center',
                    render: (h, params) => {
                        if (params.row.status === 2) {
                            return h('i-switch', {
                                style: {
                                    margin: '0 5px'
                                },
                                props: {
                                    value: params.row.hot,
                                    size: 'large',
                                    trueValue: 1,
                                    falseValue: 2
                                },
                                on: {
                                    'on-change': (hot) => {
                                        this.handleHot(params.row, hot);
                                    }
                                }
                            },
                            [
                                h('span', {
                                    slot: 'open'
                                }, '是'),
                                h('span', {
                                    slot: 'close'
                                }, '否')
                            ]
                            );
                        } else {
                            return '无';
                        }
                    }
                },
                {
                    title: '状态',
                    align: 'center',
                    render: (h, params) => {
                        const val = params.row;
                        if (val.status === 1) {
                            return h('Tag', {
                                props: {
                                    color: 'yellow'
                                }
                            }, '待发布');
                        } else if (val.status === 2) {
                            return h('Tag', {
                                props: {
                                    color: 'green'
                                }
                            }, '已发布');
                        }
                    }
                },
                {
                    title: '创建时间',
                    align: 'center',
                    key: 'createTime'
                },
                {
                    title: '操作',
                    align: 'center',
                    render: (h, params) => {
                        const row = params.row;
                        let children = [];
  
                        if (row.status === 1 && this.$hasPerms('news:update')) {
                            children.push(
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        icon: 'edit',
                                        shape: 'circle'
                                    },
                                    style: {
                                        margin: '2px 5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.handleEdit(row);
                                        }
                                    }
                                }, '编辑')
                            );
                        }
                        if (row.status === 1 && this.$hasPerms('news:publish')) {
                            children.push(
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            title: '您确定要发布吗,一旦发布不可修改?',
                                            transfer: true
                                        },
                                        on: {
                                            'on-ok': () => {
                                                this.handlePublish(params.row);
                                            }
                                        }
                                    },
                                    [
                                        h('Button', {
                                            props: {
                                                type: 'success',
                                                size: 'small',
                                                icon: 'ios-paperplane-outline',
                                                shape: 'circle'
                                            },
                                            style: {
                                                margin: '2px 5px'
                                            }
                                        }, '发布')
                                    ])
                            );
                        }
                        if (row.status === 1 && this.$hasPerms('news:delete')) {
                            children.push(
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            title: '您确定要删除吗?',
                                            transfer: true
                                        },
                                        on: {
                                            'on-ok': () => {
                                                this.handleDelete(row);
                                            }
                                        }
                                    },
                                    [
                                        h('Button', {
                                            props: {
                                                type: 'error',
                                                size: 'small',
                                                icon: 'trash-a',
                                                shape: 'circle'
                                            },
                                            style: {
                                                margin: '2px 5px'
                                            }
                                        }, '删除')
                                    ])
                            );
                        }
                        if (row.status === 2 && this.$hasPerms('news:takenDown')) {
                            children.push(
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            title: '您确定要下架吗?',
                                            transfer: true
                                        },
                                        on: {
                                            'on-ok': () => {
                                                this.takeDown(row);
                                            }
                                        }
                                    },
                                    [
                                        h('Button', {
                                            props: {
                                                type: 'error',
                                                size: 'small',
                                                icon: 'briefcase',
                                                shape: 'circle'
                                            },
                                            style: {
                                                margin: '2px 5px'
                                            }
                                        }, '下架')
                                    ])
                            );
                        }
                        return h('div', children);
                    }
                }
            ],
            // 数据
            matchs: [],
            total: 0,
            currentPage: 1,
            statusDicts: [
                {
                    lable: '待审核',
                    id: 1
                }, {
                    lable: '正常',
                    id: 2
                }, {
                    lable: '已拒绝',
                    id: 3
                }, {
                    lable: '已删除',
                    id: 4
                }
            ],
            rules: {
                name: [
                    {required: true, message: '名称不能为空', trigger: 'blur'}
                ]
            }
        };
    },
    methods: {
        getData () {
            this.isLoading = true;
            this.$get('/news/list?pageNum=' + this.currentPage, this.searchData)
                .then(res => {
                    this.matchs = res.records;
                    this.total = res.total;
                    this.currentPage = res.current;
                    this.isLoading = false;
                })
                .catch(fail => {
                    this.isLoading = false;
                });
        },
        cancelModal () {
            this.addModal = false;
        },
        handleHot (val, hot) {
            console.log(val);
            console.log(hot);
            let url = '/news/hot/';
            if (hot === 2) {
                url = '/news/unhot/';
            }
            this.$post(url + val.id)
                .then(res => {
                    this.$Message.success('操作成功！');
                })
                .catch(error => {
                    this.$Message.error(error.message);
                });
        },
        handlePublish (val) {
            console.log(val);
            this.$post('/news/publish/' + val.id)
                .then(res => {
                    this.getData();
                    this.$Message.success('发布成功');
                })
                .catch(error => {
                    this.$Message.success(error.message);
                });
        },
        handleEdit (val) {
            this.$router.push({
                name: 'news_edit',
                params: {
                    id: val.id
                }
            });
        },
        takeDown (val) {
            this.$get('/news/takeDown/' + val.id)
                .then(res => {
                    this.getData();
                    this.$Message.success('“' + val.title + '” 已成功下架');
                })
                .catch(error => {
                    this.$Message.success(error.message);
                });
        },
        addModalOk () {
            this.$refs.addFrom.validate((valid) => {
                if (valid) {
                    let url = '/news/update';
                    if (this.isAddmatch) {
                        url = '/news/save';
                    }
                    this.saveLoading = true;
                    this.$post(url, {
                        id: this.addFrom.id === 0 ? null : this.addFrom.id,
                        name: this.addFrom.name,
                        contacts: this.addFrom.contacts,
                        contactsPhone: this.addFrom.contactsPhone
                    }, 'json')
                        .then(res => {
                            this.getData();
                            this.$Message.success('操作成功');
                            this.addModal = false;
                            this.saveLoading = false;
                        })
                        .catch(error => {
                            this.saveLoading = false;
                            this.$Message.error(error.message);
                        });
                } else {
                    this.saveLoading = false;
                    // 获取表单域所有field
                    let fields = this.$refs.addFrom.fields;
                    // 聚焦错误表单域
                    try {
                        fields.forEach(element => {
                            if (element.validateState === 'error') {
                                // 这里的element无foucs()
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                // 抛出异常跳出循环
                                foreach.break = new Error('StopIteration');
                            }
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        handleDelete (val, index) {
            // 删除
            this.$get('/news/delete/' + val.id
            ).then(res => {
                this.matchs.splice(index, 1);
                this.$Message.success('删除了' + val.matchName);
                this.getData();
            }).catch(error => {
                this.$Message.error(error.message);
            });
        },
        changePage (page) {
            this.currentPage = page;
            this.getData();
        }
    },
    created () {
        this.getData();
    }
};
</script>
